<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-05-07
 * @Time: 09:56
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： aliYunOss.php
 */
namespace library;

use OSS\Core\OssException;
use OSS\OssClient;
use think\Log;

class aliYunOss {
    private static $accessKeyId;
    private static $accessKeySecret;
    private static $endpoint;
    private static $bucket;


    private static $instance = null;
    public static function getInstance():aliYunOss {
        if (empty(self::$instance)) {
            $accessKeyId = config('aliYunOSS.AccessKeyId');
            $accessKeySecret = config('aliYunOSS.AccessKeySecret');
            $endpoint = config('aliYunOSS.EndPoint');
            $bucket = config('aliYunOSS.Bucket');

            self::$instance = new self($accessKeyId, $accessKeySecret, $endpoint, $bucket);
        }
        return self::$instance;
    }

    // protected static $ossClient;
    public function __construct($accessKeyId, $accessKeySecret, $endpoint, $bucket)
    {
        self::$accessKeyId = $accessKeyId;
        self::$accessKeySecret = $accessKeySecret;
        self::$endpoint = $endpoint;
        self::$bucket = $bucket;
    }

    /**
     * ossClient
     *
     * @return OssClient
     * @throws OssException
     */
    protected static function ossClient()
    {
        return new OssClient(self::$accessKeyId, self::$accessKeySecret, self::$endpoint);
    }

    /**
     * uploadFile
     * 文件上传
     *
     * @author zhengkai
     * @date 2018-05-07
     *
     * @param string $objectFile 要保存到oss的文件(名)
     * @param string $localFile 要上传的本地文件（包含完整路径）
     * @param string $objectPath oss虚拟路径
     * @return bool|null
     */
    public static function uploadFile($objectFile, $localFile, $objectPath='')
    {
        try{
            $object = $objectPath.$objectFile;

            $upload = self::ossClient()->uploadFile(self::$bucket, $object, $localFile);

            return $upload;
        } catch(OssException $e) {
            Log::error("阿里云OSS文件上传：{$e->getMessage()}");
            return false;
        }
    }
}